<template>
  <div class="app-container">
    <div class="filter-container">
      <el-button class="filter-item" style="margin-left: 10px;" type="success" icon="el-icon-edit" @click="handleCreate">
        新增
      </el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      max-height="690"
      highlight-current-row
      style="width: 100%;"
      :row-style="{height:'32px'}"
      :default-sort="{prop: 'adminType', order: null}"
      tooltip-effect="light"
      @sort-change="sortChange"
    >
      <el-table-column label="ID" align="center" width="80" prop="adminId" sortable="custom" fixed>
        <template slot-scope="{row}">
          <span>{{ row.adminId }}</span>
        </template>
      </el-table-column>
      <el-table-column label="账号" align="center">
        <template slot-scope="{row}">
          <span>{{ row.adminUsername }}</span>
        </template>
      </el-table-column>
      <el-table-column label="昵称" align="center">
        <template slot-scope="{row}">
          <span>{{ row.adminName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="类型" align="center" prop="adminType" sortable="custom">
        <template slot-scope="{row}">
          <el-tag v-if="row.adminType===1" size="mini" type="danger">{{ adminTypeMap[row.adminType] }}</el-tag>
          <el-tag v-else-if="row.adminType===2" size="mini" type="success">{{ adminTypeMap[row.adminType] }}</el-tag>
          <el-tag v-else size="mini" type="primary">{{ adminTypeMap[row.adminType] }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="所属分局" align="center" prop="adminType" sortable="custom">
        <template slot-scope="{row}">
          <el-tag size="mini" type="primary">{{ departmentMap[row.departmentId] }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="真实姓名" align="center">
        <template slot-scope="{row}">
          <span>{{ row.realName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="手机号" align="center">
        <template slot-scope="{row}">
          <span>{{ row.phone }}</span>
        </template>
      </el-table-column>
      <el-table-column label="最近修改时间" align="center" prop="updateTime" sortable="custom">
        <template slot-scope="{row}">
          <span>{{ row.updateTime }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="260px" class-name="small-padding fixed-width" fixed="right">
        <template slot-scope="{row}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">编辑</el-button>
          <el-button type="primary" size="mini" @click="handlePwd(row)">重设密码</el-button>
          <el-button size="mini" type="danger" @click="handleDelete(row.adminId)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page-num.sync="listQuery.pageNum" :page-size.sync="listQuery.pageSize" @pagination="showAdminUserList" />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" width="35%">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-width="120px" style="width: 70%; margin-left:50px;">
        <el-form-item v-if="dialogStatus!=='pwd'" label="账号" prop="adminUsername">
          <el-input v-model="temp.adminUsername" />
        </el-form-item>
        <el-form-item v-if="dialogStatus!=='update'" label="密码" prop="adminPassword">
          <el-input v-model="temp.adminPassword" show-password />
        </el-form-item>
        <el-form-item v-if="dialogStatus!=='update'" label="再次输入密码" prop="repeatPassword">
          <el-input v-model="temp.repeatPassword" show-password />
        </el-form-item>
        <el-form-item v-if="dialogStatus!=='pwd'" label="权限类型" prop="adminType">
          <el-select v-model="temp.adminType" placeholder="请选择" clearable style="width: 150px;" class="filter-item">
            <el-option v-for="item in adminTypeList" :key="item.key" :label="item.value" :value="item.key" />
          </el-select>
        </el-form-item>
        <el-form-item v-if="dialogStatus!=='pwd'" label="分局管理权限" prop="adminType">
          <el-select v-model="temp.departmentId" placeholder="请选择" clearable style="width: 150px;" class="filter-item">
            <el-option v-for="item in departmentList" :key="item.key" :label="item.value" :value="item.key" />
          </el-select>
        </el-form-item>
        <el-form-item v-if="dialogStatus!=='pwd'" label="昵称" prop="adminName">
          <el-input v-model="temp.adminName" />
        </el-form-item>
        <el-form-item v-if="dialogStatus!=='pwd'" label="真实姓名" prop="realName">
          <el-input v-model="temp.realName" />
        </el-form-item>
        <el-form-item v-if="dialogStatus!=='pwd'" label="手机号" prop="phone">
          <el-input v-model="temp.phone" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button v-if="dialogStatus==='create'" type="primary" @click="createData()">确认</el-button>
        <el-button v-if="dialogStatus==='update'" type="primary" @click="updateData()">确认</el-button>
        <el-button v-if="dialogStatus==='pwd'" type="primary" @click="changePwd()">确认</el-button>
      </div>
    </el-dialog>
<!--    <div v-else>-->
<!--      <h3>您的账号权限不足！</h3>-->
<!--      <div>-->
<!--        <img :src="emptyGif" class="emptyGif">-->
<!--      </div>-->
<!--    </div>-->
  </div>
</template>

<script>
import { showAdminUserList, deleteAdminUser, addAdminUser, editAdminUser, changePwd, getRoleList } from '@/api/admin'
import { getDepartmentList } from '@/api/department'
import waves from '@/directive/waves' // waves directive
import Pagination from '@/components/Pagination'
import { validUsername, isPassword } from '@/utils/validate'
import rsaEncrypt from '@/utils/rsa'

export default {
  name: 'AdminManage',
  components: { Pagination },
  directives: { waves },
  data() {
    const validateUsername = (rule, value, callback) => {
      if (!validUsername(value)) {
        callback(new Error('请输入正确的账号！'))
      } else {
        callback()
      }
    }
    const validatePassword = (rule, value, callback) => {
      if (value.length < 6) {
        callback(new Error('密码不得少于6位！'))
      } else {
        callback()
      }
    }
    const validateRepeat = (rule, value, callback) => {
      if (value !== this.temp.adminPassword) {
        callback(new Error('两次输入的密码不一致！'))
      } else {
        callback()
      }
    }
    return {
      tableKey: 0,
      list: [],
      total: 0,
      listLoading: true,
      listQuery: {
        pageNum: 1,
        pageSize: 20
      },
      temp: {
        adminId: undefined,
        adminUsername: '',
        adminPassword: '',
        repeatPassword: '',
        adminType: '',
        departmentId: '',
        adminName: '',
        realName: '',
        phone: ''
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '新增',
        pwd: '重设密码'
      },
      rules: {
        adminUsername: [{ required: true, message: '请输入正确的账号', trigger: 'blur', validator: validateUsername }],
        adminPassword: [{ required: true, message: '密码不得少于6位', trigger: 'blur', validator: validatePassword }, { validator: isPassword, trigger: 'blur' }],
        repeatPassword: [{ required: true, trigger: 'blur', validator: validateRepeat }],
        departmentId: [{ required: true, message: '请设置管理员所属分局', trigger: 'change' }],
        adminType: [{ required: true, message: '请选择管理员权限类型', trigger: 'change' }],
        adminName: [{ required: true, message: '请填写管理员昵称', trigger: 'blur' }]
      },
      emptyGif: 'https://wpimg.wallstcn.com/0e03b7da-db9e-4819-ba10-9016ddfdaed3',
      adminTypeList: [
        { key: 1, value: '超级管理员' },
        { key: 2, value: '普通管理员' }
      ],
      departmentList: []
    }
  },
  computed: {
    adminType() {
      return this.$store.state.user.type
    },
    adminTypeMap: function() {
      return this.adminTypeList.reduce((acc, cur) => {
        acc[cur.key] = cur.value
        return acc
      }, {})
    },
    departmentMap: function() {
      return this.departmentList.reduce((acc, cur) => {
        acc[cur.key] = cur.value
        return acc
      }, {})
    }
  },
  created() {
    this.getDepartmentList()
    this.getRoleList()
    this.showAdminUserList()
  },
  methods: {
    getRoleList() {
      getRoleList().then(response => {
        const roleList = response.data
        const typeList = []
        for (let i = 0; i < roleList.length; i++) {
          typeList.push(
            {
              key: roleList[i].roleId,
              value: roleList[i].remarks
            }
          )
        }
        this.adminTypeList = typeList
      })
    },
    getDepartmentList() {
      getDepartmentList().then(response => {
        const tmpList = response.data
        const departmentList = []
        for (let i = 0; i < tmpList.length; i++) {
          departmentList.push(
            {
              key: tmpList[i].departmentId,
              value: tmpList[i].departmentName
            }
          )
        }
        this.departmentList = departmentList
      })
    },
    showAdminUserList() {
      this.listLoading = true
      showAdminUserList(this.listQuery).then(response => {
        this.list = response.data.list
        this.total = response.data.total
        this.listLoading = false
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.showAdminUserList()
    },
    sortChange(data) {
      const { prop, order } = data
      this.listQuery.sortProp = prop
      if (order === 'ascending') {
        this.listQuery.sortOrder = '1'
      } else {
        this.listQuery.sortOrder = '-1'
      }
      this.handleFilter()
    },
    resetDialog() {
      this.temp = {
        adminId: undefined,
        adminUsername: '',
        adminPassword: '',
        repeatPassword: '',
        adminType: '',
        departmentId: '',
        adminName: '',
        realName: '',
        phone: ''
      }
    },
    handleCreate() {
      this.resetDialog()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const passwordEncrypt = rsaEncrypt(this.temp.adminPassword)
          const data = Object.assign({}, this.temp)
          data.adminPassword = passwordEncrypt
          addAdminUser(data).then(() => {
            this.showAdminUserList()
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: '添加账号成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          editAdminUser(this.temp).then(() => {
            this.showAdminUserList()
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: '编辑账号成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handlePwd(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.dialogStatus = 'pwd'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    changePwd() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const passwordEncrypt = rsaEncrypt(this.temp.adminPassword)
          const data = Object.assign({}, this.temp)
          data.adminPassword = passwordEncrypt
          changePwd(data).then(() => {
            this.showAdminUserList()
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: '修改密码成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleDelete(adminId) {
      this.$confirm('此删除操作不可逆, 是否继续?', '提示', {
        confirmButtonText: '确认删除',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteAdminUser(adminId).then(() => {
          this.showAdminUserList()
          this.dialogFormVisible = false
          this.$notify({
            title: 'Success',
            message: '删除管理员成功',
            type: 'success',
            duration: 2000
          })
        })
      })
    }
  }
}
</script>

<style lang="scss" scoped>
  .emptyGif {
    display: block;
    width: 45%;
    margin: 0 auto;
  }
</style>
